<template>
  <div class="role">
    <div class="search">
      <el-button size="small" type="primary" @click="editRef.drawer = true">添加</el-button>
    </div>
    <el-table size="small" :data="showRoles" style="width: 98%;">
      <el-table-column prop="roleId" label="编号" width="100" />
      <el-table-column prop="roleName" label="名称" width="250" />
      <el-table-column label="操作">
        <template #default="scope">
          <el-button size="small" type="success" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row.roleId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination :page-size="5" style="margin-top: 5px;" size="small" background layout="prev, pager, next"
      :total="roles.length" v-model:current-page="pageIndex" />
    <EditRole ref="editRef" @sync-list="loadRoles" @update="handleUpdate"></EditRole>
  </div>
</template>

<script lang="ts" setup>
import EditRole from '../../components/user/EditRole.vue'
import { onMounted, ref, computed } from 'vue'
import { $list, $delete, $getOne } from '../../api/role'
import { ElMessageBox, ElNotification } from "element-plus";

// 角色列表
interface FormDataInt {
  roleId: number,
  roleName: string
}
let roles = ref([])
let pageIndex = ref(1)

let showRoles = computed(() => {
  return roles.value.slice((pageIndex.value - 1) * 5, pageIndex.value * 5)
})
// 加载角色列表
const loadRoles = async () => {
  roles.value = await $list()
}

const handleUpdate = (payload: FormDataInt) => {
  console.log(payload);
}

const handleEdit = async (row: any) => {
  let ret = await $getOne(row.roleId)

  editRef.value.formData = row
  editRef.value.drawer = true
}

const handleDelete = (roleId: number) => {
  ElMessageBox.confirm(
    '确定删除吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    let ret = await $delete({ roleId })
    if (ret.success) {
      ElNotification({
        title: '提示',
        message: ret.message,
        type: 'success',
      })
      loadRoles()
    } else {
      ElNotification({
        title: '提示',
        message: ret.message,
        type: 'error',
      })
    }
  }).catch(() => {

  })
}

// 定义编辑组件 ref 对象
let editRef = ref({
  drawer: false,
  formData: {
    roleId: 0,
    roleName: ''
  }
})

onMounted(() => {
  loadRoles()
})

</script>

<style scoped lang="scss">
.search {
  margin-bottom: 5px;
}
</style>
